package uri.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import uri.model.BoardVO;
import uri.model.MemberVO;
import uri.model.FileVO;
import uri.model.collection.CollectionListVO;
import uri.model.collection.CollectionService;
import uri.model.collection.CommentVO;

@Controller
public class CollectionController {

	@Resource(name="collectionServiceImpl")
	private CollectionService collectionService;
	
	private String path="C:\\java-kosta\\goodjob-workspace\\goodjob-ver1\\WebContent\\WEB-INF\\view\\fileupload\\";
	
	@RequestMapping("collection/auth_writeCollectionGo.do")
	public String writeCollectionGo(){
		return "writeCollection.collection";
	}
	
	@RequestMapping("collection/auth_writeCollection.do")
	public ModelAndView writeCollection(BoardVO bvo,HttpSession session){
		//BoardVO 정보를 DB에 저장하는 구현부
		MemberVO vo=(MemberVO) session.getAttribute("loginMember");
		System.out.println("세션 정보 : "+vo);
		bvo.setMemberVO(vo);
		collectionService.writeCollection(bvo);
		System.out.println("sql insert 후  bvo : "+bvo);
		
		
		//파일을 DB에 저장하는 구현부
		List<MultipartFile> fileList=bvo.getFiles();
		System.out.println("fileList : "+fileList);
		
		FileVO fvo=new FileVO();
		for(int i=0;i<fileList.size();i++){
			String orgFileName=fileList.get(i).getOriginalFilename();
			if(!orgFileName.equals("")){
				try {
					//nameList.add(orgFileName);
					long now=System.currentTimeMillis();			
					//newfilename=now+"_"+mFile.getOriginalFilename();
					String newFileName=now+"_"+orgFileName;
					fileList.get(i).transferTo(new File(path+newFileName));
					fvo.setNewFileName(newFileName);
					fvo.setOrgFileName(orgFileName);
					fvo.setId(bvo.getMemberVO().getId());
					fvo.setTextNo(bvo.getNo());
					collectionService.fileUpload(fvo);
					System.out.println("fileupload ok :"+newFileName);
				} catch (IllegalStateException | IOException e) {
					e.printStackTrace();
					System.out.println("파일 업로드 실패임");
				}
			}
		}
		System.out.println("글쓰기 완료");
		return new ModelAndView("redirect:/collection/auth_detailCollectionNoHit.do?no="+bvo.getNo());
	}
	
	@RequestMapping("collection/auth_detailCollectionNoHit.do")
	public ModelAndView detailCollectionNoHit(String no){
		System.out.println("detailCollectionNoHit");
		BoardVO bvo=(BoardVO)collectionService.detailCollectionNoHit(no);
		System.out.println("디테일 정보 : "+bvo);
		
		List<FileVO> fileList=collectionService.fileInfo(no);
		System.out.println("파일정보 : "+fileList);
		
		HashMap detailInfo=new HashMap();
		detailInfo.put("fileList", fileList);
		detailInfo.put("bvo", bvo);
		System.out.println("detailInfo 맵 정보 : "+ detailInfo);
		return new ModelAndView("detail.collection","detailInfo",detailInfo);
	}
	
	@RequestMapping("collection/auth_detailCollectionHitPlus.do")
	public ModelAndView detailCollectionHitPlus(String no,@CookieValue(value="no",required=false)String cookieValue,HttpServletResponse response){
		System.out.println("detailCollectionHitPlus");
		
		if(cookieValue==null){ 
			Cookie cookie = new Cookie("no","|"+no+"|"); 
			cookie.setMaxAge(60); //60초간 지속
			System.out.println("쿠키가 없으면 쿠키를 생성하여준다. ");
			response.addCookie(cookie);
			collectionService.hitPlus(no); 
			System.out.println("조회수 증가");
		}else{
			if(cookieValue.indexOf(no)==-1){ 
				System.out.println("쿠키가 있으면 no가 쿠키의 요소에 없으면");
				Cookie cookie = new Cookie("no",cookieValue+"|"+no+"|");
				cookie.setMaxAge(60); //60초간 지속
				response.addCookie(cookie);
				collectionService.hitPlus(no);
				System.out.println("조회수 증가");
			}
		}	
		BoardVO bvo = collectionService.detailCollectionNoHit(no);
		System.out.println("디테일 정보 : "+bvo);
		
		List<FileVO> fileList=collectionService.fileInfo(no);
		System.out.println("파일정보 : "+fileList);
		
		HashMap detailInfo=new HashMap();
		detailInfo.put("fileList", fileList);
		detailInfo.put("bvo", bvo);
		System.out.println("detailInfo 맵 정보 : "+ detailInfo);
		return new ModelAndView("detail.collection","detailInfo",detailInfo);
	}
	
	@RequestMapping("collection/contentList.do")
	public ModelAndView contentList(String nowPage){
		System.out.println("contentList");
		System.out.println(nowPage);
		CollectionListVO collectionListVO=collectionService.contentList(nowPage);
		System.out.println("리스트 전달값 : "+collectionListVO);
		return new ModelAndView("contentList.collection","collectionListVO",collectionListVO);
	}
	
	/**
	 * @작성자 : 정기남 
	 * @날짜 : 2014-07-01
	 * @메서드 : 게시글을 지우는 메서드(파일도 지워짐) 
	 */
	@RequestMapping("collection/auth_deleteCollection.do")
	public ModelAndView deleteCollection(String no){
		System.out.println("deleteCollection");
		collectionService.deleteFiles(no,path);
		collectionService.deleteCollection(no);
		return new ModelAndView("redirect:/collection/contentList.do");
	}
	
	@RequestMapping("collection/auth_updateCollection.do")
	public ModelAndView updateCollection(String no){
		System.out.println("updateCollection");
		BoardVO bvo=collectionService.detailCollectionHitPlus(no);
		System.out.println(bvo);
		List<FileVO> fileList=collectionService.fileInfo(no);
		HashMap detailInfo=new HashMap();
		detailInfo.put("fileList", fileList);
		detailInfo.put("bvo", bvo);
		System.out.println("detailInfo 맵 정보 : "+ detailInfo);
		return new ModelAndView("updateInfo.collection","detailInfo",detailInfo);
	}
	
	@RequestMapping("collection/auth_updateCollectionGo.do")
	public ModelAndView updateCollectionGo(BoardVO bvo,HttpSession session, HttpServletRequest request){
		System.out.println("updateCollectionGo");
		MemberVO mvo=(MemberVO) session.getAttribute("loginMember");
		bvo.setMemberVO(mvo);
		
		List<FileVO> beforeFile=collectionService.fileInfo(bvo.getNo());
		System.out.println("beforeFile : "+beforeFile);
		List<MultipartFile> fileList=bvo.getFiles();
		System.out.println("fileList size: "+fileList.size());
		for(int i=0;i<fileList.size();i++){
			System.out.println(fileList.get(i).getOriginalFilename().isEmpty());
			System.out.println("파일리스트 이름 : "+fileList.get(i).getOriginalFilename());
		}
		FileVO fvo=new FileVO();
			
		if(beforeFile.size()!=0){ //기존의 파일이 있는 경우
			System.out.println("기존의 파일이 있는 경우");
			for(int i=0;i<fileList.size();i++){
				String orgFileName=fileList.get(i).getOriginalFilename();
				System.out.println(orgFileName);
				collectionService.deleteFile(beforeFile.get(i).getNo(), path);//i 번째 기존 파일 삭제
				System.out.println(i+"번째 기존파일 삭제");
				
				if(!orgFileName.equals("")){ //i 번째 새로 추가한 파일이 있으면 
					System.out.println(i+"번째 새로 추가한 파일이 있으면");
					try {
						//nameList.add(orgFileName);
						long now=System.currentTimeMillis();			
						//newfilename=now+"_"+mFile.getOriginalFilename();
						String newFileName=now+"_"+orgFileName;
						fileList.get(i).transferTo(new File(path+newFileName));
						fvo.setNewFileName(newFileName);
						fvo.setOrgFileName(orgFileName);
						fvo.setId(bvo.getMemberVO().getId());
						fvo.setTextNo(bvo.getNo());
						collectionService.fileUpload(fvo);
						System.out.println("fileupload ok :"+newFileName);
					} catch (IllegalStateException | IOException e) {
						e.printStackTrace();
						System.out.println("파일 업로드 실패임");
					}//catch
				}//if
			}//for
			/*if(beforeFile.size()==1){	//기존 파일이 1개일 경우
				
			}else if(beforeFile.size()==2){	//기존 파일이 2개일 경우
				
			}else{		//기존 파일이 3개일 경우
				
			}*/
			
			
		}//if
		else{ //기존의 파일이 없을경우 
			for(int i=0;i<fileList.size();i++){
				String orgFileName=fileList.get(i).getOriginalFilename();
				if(!orgFileName.equals("")){ //새로운 파일이 존재 할 경우
					try {
						//nameList.add(orgFileName);
						long now=System.currentTimeMillis();			
						//newfilename=now+"_"+mFile.getOriginalFilename();
						String newFileName=now+"_"+orgFileName;
						fileList.get(i).transferTo(new File(path+newFileName));
						fvo.setNewFileName(newFileName);
						fvo.setOrgFileName(orgFileName);
						fvo.setId(bvo.getMemberVO().getId());
						fvo.setTextNo(bvo.getNo());
						collectionService.fileUpload(fvo);
						System.out.println("fileupload ok :"+newFileName);
					} catch (IllegalStateException | IOException e) {
						e.printStackTrace();
						System.out.println("파일 업로드 실패임");
					}//catch
				}//if
			}//for
			
		}//else
					
		//게시글 업데이트 정보
		System.out.println("수정전 : "+bvo);
		collectionService.updateCollection(bvo);
		System.out.println("수정후 : "+bvo);
		
		//System.out.println(fvo);
		return new ModelAndView("redirect:/collection/auth_detailCollectionNoHit.do?no="+bvo.getNo());
	}
	
	/*@RequestMapping("collection/updateCollectionGo.do")
	public ModelAndView updateCollectionGo(String no){
		return new ModelAndView("");
	}*/
	/**
	 * @작성자 : 정기남 
	 * @날짜 : 2014-07-01
	 * @메서드 : 파일 다운로드를 받는 메서드 
	 */
	@RequestMapping("collection/auth_fileDownload.do")
	public ModelAndView fileDownload(String newfilename,String orgfilename){
		System.out.println("fileDownload.do 실행");
		HashMap map = new HashMap();
		map.put("path", path);
		map.put("newfilename",newfilename);
		map.put("orgfilename", orgfilename);
		return new ModelAndView("downloadView",map);
	}
	
	
	
	
	//여기서부터 댓글관련 구현부
	/**
	 * @작성자 : 정기남 
	 * @날짜 : 2014-07-01
	 * @메서드 : 게시글에 대한 댓글을 쓰는 메서드
	 */
	@RequestMapping("collection/auth_writeComment.do")
	@ResponseBody
	public boolean writeComment(CommentVO cvo){
		System.out.println("writeComment");
		System.out.println("전 : "+ cvo);
		int index=collectionService.writeComment(cvo);
		System.out.println("후 : "+cvo);
		boolean flag = false;
		if(index>0){ //반환값이 0이상인 경우 (등록된경우)
			flag=true; //true를 반환
		}
		return flag;
	}
	
	/**
	 * @작성자 : 정기남 
	 * @날짜 : 2014-07-01
	 * @메서드 : 게시글에 대한 모든 댓글을 가져오는 메서드
	 */
	@RequestMapping("collection/auth_getAllComment.do")
	@ResponseBody
	public List<CommentVO> getAllComment(String no){
		System.out.println("getAllComment.do 실행");
		System.out.println(no);
		List<CommentVO> list=collectionService.getAllComment(no);
		System.out.println(list);
		return list;
	}
	
	/**
	 * @작성자 : 정기남 
	 * @날짜 : 2014-07-02
	 * @메서드 : 게시글에 대한 댓글을 지우는 메서드
	 */
	@RequestMapping("collection/auth_deleteComment.do")
	@ResponseBody
	public boolean deleteComment(String no){
		System.out.println("deleteComment");
		int index=collectionService.deleteComment(no);
		boolean flag = false;
		if(index>0){ //반환값이 0이상인 경우 (등록된경우)
			flag=true; //true를 반환
		}
		return flag;
	}
	
	/**
	 * @작성자 : 정기남 
	 * @날짜 : 2014-07-02
	 * @메서드 : 게시글에 대한 댓글을 수정하는 메서드
	 */
	@RequestMapping("collection/auth_updateComment.do")
	@ResponseBody
	public boolean updateComment(CommentVO cvo){
		System.out.println("updateComment");
		System.out.println(cvo);
		int count=collectionService.updateComment(cvo);
		boolean flag=false;
		if(count==0){
			return flag;
		}else{
			return true;
		}
	}
	
	
	//여기서부터 답글에 관련된 구현부
	@RequestMapping("collection/auth_replyWrite.do")
	public ModelAndView replyWrite(String no,String ref){
		System.out.println("replyWrite");
		BoardVO bvo=collectionService.detailCollectionNoHit(no);
		bvo.setRef(Integer.parseInt(ref));
		System.out.println(bvo);
		return new ModelAndView("replyWrite.collection","bvo",bvo);
	}
	
	@RequestMapping("collection/auth_replyWriteGo.do")
	public ModelAndView replyWriteGo(BoardVO bvo,HttpSession session){
		System.out.println("replyWriteGo");
		MemberVO loginMember=(MemberVO) session.getAttribute("loginMember");
		bvo.setMemberVO(loginMember);
		System.out.println("ref를 보고파 : "+bvo.getRef());
		System.out.println("no를 보고파 : "+bvo.getNo());
		collectionService.replyWriteGo(bvo);
		System.out.println(bvo);
		return new ModelAndView("redirect:/collection/auth_replyWriteDetailNohit.do?no="+bvo.getNo());
	}
	@RequestMapping("collection/auth_replyWriteDetailNohit.do")
	public ModelAndView replyWriteDetailNohit(String no){
		System.out.println("replyWriteDetailNohit");
		BoardVO bvo = collectionService.detailCollectionNoHit(no);
		System.out.println("no "+bvo.getNo());
		System.out.println("REF "+bvo.getRef());
		System.out.println("답글 디테일 정보 : "+bvo);
		return new ModelAndView("replyWriteDetail.collection","bvo",bvo);
	}
	
	@RequestMapping("collection/auth_replyWriteDetail.do")
	public ModelAndView replyWriteDetail(String no,@CookieValue(value="no",required=false)String cookieValue,HttpServletResponse response){
		System.out.println("replyWriteDetail");
		if(cookieValue==null){ 
			Cookie cookie = new Cookie("no","|"+no+"|"); 
			cookie.setMaxAge(60); //60초간 지속
			System.out.println("쿠키가 없으면 쿠키를 생성하여준다. ");
			response.addCookie(cookie);
			collectionService.hitPlus(no); 
			System.out.println("조회수 증가");
		}else{
			if(cookieValue.indexOf(no)==-1){ 
				System.out.println("쿠키가 있으면 no가 쿠키의 요소에 없으면");
				Cookie cookie = new Cookie("no",cookieValue+"|"+no+"|");
				cookie.setMaxAge(60); //60초간 지속
				response.addCookie(cookie);
				collectionService.hitPlus(no);
				System.out.println("조회수 증가");
			}
		}	
		BoardVO bvo = collectionService.detailCollectionNoHit(no);
		System.out.println("답글 디테일 정보 : "+bvo);
		return new ModelAndView("replyWriteDetail.collection","bvo",bvo);
	}
	
	@RequestMapping("collection/auth_replyUpdate.do")
	public ModelAndView auth_replyUpdate(String no){
		System.out.println("auth_replyUpdate");
		BoardVO bvo=collectionService.detailCollectionNoHit(no);
		System.out.println(bvo);
		return new ModelAndView("replyUpdate.collection","bvo",bvo);
	}
	
	@RequestMapping("collection/auth_replyUpdateGo.do")
	public ModelAndView auth_replyUpdateGo(BoardVO bvo){
		System.out.println("auth_replyUpdateGo");
		collectionService.updateCollection(bvo);
		return new ModelAndView("redirect:/collection/auth_replyWriteDetailNohit.do?no="+bvo.getNo());
	}
	
	//여기서부터 검색 관련 구현부
	@RequestMapping("collection/findCollectionByTitle.do")
	public ModelAndView findCollectionByTitle(String word,String nowPage){
		System.out.println("findCollectionByTitle");
		CollectionListVO collectionListVO=collectionService.findCollectionByTitle(word,nowPage);
		if(collectionListVO.getList().size()==0){
			return new ModelAndView("findFail.collection");
		}
		System.out.println(collectionListVO);
		return new ModelAndView("findCollectionByTitle.collection","collectionListVO",collectionListVO);
	}
	
	@RequestMapping("collection/findCollectionByContent.do")
	public ModelAndView findCollectionByContent(String word,String nowPage){
		System.out.println("findCollectionByContent");
		CollectionListVO collectionListVO=collectionService.findCollectionByContent(word,nowPage);
		if(collectionListVO.getList().size()==0){
			return new ModelAndView("findFail.collection");
		}
		return new ModelAndView("findCollectionByContent.collection","collectionListVO",collectionListVO);
	}
	
	@RequestMapping("collection/findCollectionByTitleAndContent.do")
	public ModelAndView findCollectionByTitleAndContent(String word,String nowPage){
		System.out.println("findCollectionByTitleAndContent");
		CollectionListVO collectionListVO=collectionService.findCollectionByTitleAndContent(word,nowPage);
		if(collectionListVO.getList().size()==0){
			return new ModelAndView("findFail.collection");
		}
		return new ModelAndView("findCollectionByTitleAndContent.collection","collectionListVO",collectionListVO);
	}
	
	/**
	 * 박현종 7-11 13:59
	 *  no에 해당하는 게시물 추천하기
	 *  Ajax
	 */
	@RequestMapping("collection/auth_updateLike.do")
	@ResponseBody
	public boolean updateLike(String no,@CookieValue(value="like",required=false)String cookieValue,
									HttpServletResponse response){ //no이름의 쿠키를 가져온다 
		System.out.println("detatilBoard.do 실행");
		boolean flag = true;
		
		if(cookieValue==null){//쿠키가 없으면 
			Cookie cookie = new Cookie("like","|"+no+"|"); 
			cookie.setMaxAge(86400); //24시간 지속
			//쿠키를 생성하여준다 
			response.addCookie(cookie);
			collectionService.updateLike(no); //추천수 증가
		}else{//쿠키가 있으면 
			if(cookieValue.indexOf(no)==-1){ //no가 쿠키의 요소에 없으면
				Cookie cookie = new Cookie("like",cookieValue+"|"+no+"|");
				cookie.setMaxAge(86400); //24시간 지속
				response.addCookie(cookie);
				collectionService.updateLike(no); //추천수 증가
			}else{//쿠키 요소가 있으면 
				flag = false;
			}
		}
		
		return flag;
	}
	
	
	
	
	
	
	
}//class




